import Vue from 'vue'
import Vuex from 'vuex'
// import Cookies from 'js-cookie'
import router from '@/router/index'
// import ajax from '@/api/ajax'
import { menuList, addRouterList } from './menuData'
import {
  Message
} from 'element-ui'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    windowSize: null,
    user: {
      phoneNo: '',
      userState: ''
    },
    sessionId: ''
  },
  mutations: {
    updateSize(state, size) {
      state.windowSize = size
    },
    updateToken(state, data) {
      if (data) {
        const {
          phoneNo,
          userState
        } = data
        state.user.phoneNo = phoneNo
        // Cookies.set('imPhoneNo', phoneNo)
        // Cookies.set('imIsLogin', isLogin)
        localStorage.setItem('userState', userState)
        localStorage.setItem('sessionId', '111111')
        localStorage.setItem('phoneNo', phoneNo)
      } else {
        state.user.phoneNo = null
        // Cookies.remove('imPhoneNo')
        // Cookies.remove('imIsLogin')
        localStorage.removeItem('phoneNo')
        localStorage.removeItem('sessionId')
        localStorage.removeItem('userState')
        localStorage.removeItem('addUser')
        localStorage.removeItem('adminUser')
        localStorage.removeItem('navList')
      }
    }
  },
  actions: {
    addRoute({ commit, dispatch }) { // 动态根据权限添加路由
      let addRoutes = []
      let tempList = []
      let rolesUser = localStorage.getItem('adminUser')
      addRouterList.forEach(item => {
        tempList = []
        if (item.children) {
          item.children.forEach(item2 => {
            let isRole = item2.meta.roles.some(m => m === rolesUser)
            if (item2.meta.roles && isRole && menuList.find(m => m.url === item2.path)) {
              tempList.push(item2)
            }
            if (tempList.length > 0) {
              addRoutes.push(Object.assign({}, item, {
                children: tempList
              }))
            }
            localStorage.setItem('navList', JSON.stringify(tempList))
          })
        }
        router.addRoutes(addRoutes)
      })
    },
    async login({ commit, dispatch }, params) {
      commit('updateToken', {
        phoneNo: params.phoneNo,
        userState: params.userState
      })
      dispatch('addRoute')
      return Promise.resolve()
    },
    async logout({ commit, dispatch }) {
      commit('updateToken')
      router.push('/login')
    },
    authSubmit({ commit, dispatch }, params) {
      // 实名认证
      localStorage.setItem('userState', '00')
      Message({
        message: '您已提交实名认证，业务人员将在1-2日内为您审核',
        type: 'success'
      })
      router.push('/user/info')
    }
  }
})
export default store